import React, {useState, useEffect, useCallback} from 'react';
import {
  Table, Checkbox, Row, Modal, Form, Input, Col, message, InputNumber, Select, Button, Radio, DatePicker, Upload,
} from 'antd';
import {
  addCommonsAlbum,
  delOnePic,
  getAlbumPicture,
} from '@/services/goodCenter/goods'
import { formItemLayout } from '@/utils/utils';
import styles from './index.less'
import Cropper from 'react-cropper'
import 'cropperjs/dist/cropper.css'
import { connect } from 'dva';

const { Dragger } = Upload;
const { Option } = Select

const AddAlbum = (Form.create())(props => {
  const { picList,  setVisibleState, form } = props
  const { validateFieldsAndScroll, getFieldDecorator, } = form
  const [visible, setVisible] = useState(false)
  const [aId, setAId] = useState(null) // 相册id

  useEffect(() => {
    setVisible(setVisibleState)
  }, [setVisibleState])

  const _addAlbum = (e) => {
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        addCommonsAlbum({
          resCommonsAlbum: values,
        }).then(res => {
          message.info(res.msg)
          setVisible(!visible)
        })
      }
    });
  }

  return (
    <Modal
      visible={visible}
      onOk={_addAlbum}
      title='添加本地相册'
      onCancel={() => setVisible(!visible)}
    >
      <Form {...formItemLayout}>
        <Form.Item label="上级相册">
          {getFieldDecorator('albumParentId', {
          })(<Select placeholder="请选择相册" onChange={val => setAId(val)}>
            <Option value={'0'}>顶级相册</Option>
            {picList.map(r => <Option key={r.id} value={r.id}>{r.albumName}</Option>)}
          </Select>)}
        </Form.Item>
        <Form.Item label="相册名称">
          {getFieldDecorator('albumName', {
          })(<Input placeholder="请输入相册名称" />)}
        </Form.Item>
      </Form>
    </Modal>
  )
})


const SelectAlbumPic = connect(({goods}) => ({goods}))(props => {
  const { data, modalVisible, dispatch, goods, handleVisible } = props
  const { selectPics } = goods
  const list = []

  const selectPic = useCallback((pic) => {
    list.push(pic)
    dispatch({
      type: 'goods/saveData',
      payload: {
        selectPics: [
          ...selectPics,
          ...list,
        ]
      }
    })
    handleVisible(!modalVisible)
  }, [modalVisible])

  return (
    <Modal
      visible={modalVisible}
      onCancel={() => handleVisible(!modalVisible)}
      footer={null}
    >
      {
        data.resCommonsAlbumImages && data.resCommonsAlbumImages.map(d => (
          <Row key={d.id} style={{marginBottom: 10, borderBottom: '1px solid #dfdfdf'}}>
            <Col span={6}>
              <img src={d.imageUrl} style={{width: 100, height: 100}} />
            </Col>
            <Col span={12}>
              <div>图片类型：{d.imageTypeText}</div>
              <div>图片高度：{d.imageHeight}</div>
              <div>图片宽度：{d.imageWidth}</div>
              <div>图片存储大小：{d.imageStorageSize}</div>
            </Col>
            <Col span={6}>
              {
                d.groupId != d.id && data.resCommonsAlbumImages.length > 1 ?
                <Button style={{ marginTop: 30 }}  type='primary' onClick={selectPic.bind(this, d)}>选取</Button> :
                data.resCommonsAlbumImages.length == 1 ?
                <Button style={{ marginTop: 30 }}  type='primary' onClick={selectPic.bind(this, d)}>选取</Button> :
                null
              }
            </Col>
          </Row>
        ))
      }
    </Modal>
  )
})

/**
 * notice: 剪裁 选中图片删减 图片被选中样式 未完成
 *
 * @param {func} onUseSelectPhoto 选中使用图片
 * @param {Array} picList 我的相册列表
 * @param {String} albumId 默认相册id
 */
const AlbumUpload = props => {
  const { addAlbum, picList, albumId, onUseSelectPhoto, goods, } = props
  const { selectPics } = goods
  const [curPic, setcurPic] = useState('');
  const [albumState, setAlbumState] = useState(false) // 选择相册
  const [picState, setPicState] = useState(false) // 选择照片大小状态
  const [mycropper, setmycropper] = useState(''); // 剪裁
  const [curUrl, setcurUrl] = useState(''); // 剪裁地址
  const [imgsList, setImgList] = useState([])
  const [picDetails, setPicDetails] = useState([])

  useEffect(() => {
    setcurPic(albumId)
    init({
      resCommonsAlbumImage: {
        albumId: albumId,
      },
      pageNo: 1,
      pageSize: 50
    })
  }, [albumId])

  const cropper = React.createRef(null);

  const init = async (params) => {
    const res = await getAlbumPicture(params)
    setImgList(res.data || [])
  }

  const options = {
    action: '/Amaidan-Goods-Web/common/uploadImage',
    multiple: true,
    beforeUpload(file, fileList) {
      console.log(file, fileList)
    },
    headers: {
      'token': '1f763f2810d24a86b68d1dc862367ec4',
    }
  };

  const _crop = () => {
    // image in dataUrl
    console.log(this.refs.cropper.getCroppedCanvas().toDataURL());
  }

  const useSelectPhoto = () => {
    onUseSelectPhoto(selectPics)
  }


  const deletePic = async (id) => {
    const res = await delOnePic({
      imageId: id,
    })
    message.info(res.msg)
    init({
      resCommonsAlbumImage: {
        albumId: curPic,
      },
      pageNo: 1,
      pageSize: 50
    })
  }

  const renderImgs = useCallback(() => {
    const choosePic = (val) => {
      // console.log(val)
      setPicState(!picState)
      setPicDetails(val)
    }

    return (
      imgsList.length > 0 && imgsList.map((val, i) => (
        <Col xs={12} sm={6} key={val.standardImageId} style={{paddingBottom: 20}}>
          <div className="aimg">
            <div className="imgBox">
              <img style={{width: 100, height: 100}} src={val.standardImageUrl} alt=""/>
            </div>
            <div
              style={{width: 100, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis'}}
            >
              {val.standardImageName}
            </div>
            <div className="imgBtn">
              <Button type="primary" size="small" onClick={choosePic.bind(this, val)}>选择</Button>
              <Button type="danger" size="small" onClick={deletePic.bind(this, val.standardImageId)}>删除</Button>
            </div>
          </div>
        </Col>
      ))
    )
  }, [imgsList])

  const changeAlbum = val => {
    setcurPic(val.target.value)
    init({
      resCommonsAlbumImage: {
        albumId: val.target.value,
      },
      pageNo: 1,
      pageSize: 50
    })
  }

  // 处理子模态框modal
  const handleVisible = (state) => {
    setPicState(state)
  }


  return (
    <Row>
      <Col span={8}>
        <div className="imgbox-left">
          <div className="imgbox-title btween" style={{borderRight: 0}}>
            <span>我的相册</span>
            <Button type="primary" onClick={() => setAlbumState(!albumState)}>添加相册</Button>
          </div>
          <div className="imgbox-body" style={{borderRight: 0}}>
            <Radio.Group value={curPic} onChange={changeAlbum}>
              { picList.map(v => (<Row key={v.id}><Radio value={v.id}>{v.albumName}</Radio></Row>)) }
            </Radio.Group>
          </div>
        </div>
      </Col>
      <Col span={16}>
        <div className="imgbox-right">
          <div className="imgbox-title" style={{ lineHeight: '32px',}}>图片库</div>
          <Row className={styles.btnBox}>
            <Col span={3}>
              <Dragger {...options}>
                <Button type="primary">上传图片</Button>
              </Dragger>
            </Col>
            <Col offset={18} className={styles.btnStyle}>
              <Button type='primary' style={{marginRight: 10}} onClick={useSelectPhoto}>使用选中图片</Button>
              <Button type='primary'>剪裁</Button>
            </Col>
          </Row>
          <Row gutter={15} className="imgbox-body" style={{margin: 0}}>
            { imgsList.length > 0 ? renderImgs() : (<span>暂无图片</span>) }
          </Row>
        </div>
      </Col>
      <AddAlbum picList={picList} setVisibleState={albumState} />
      <SelectAlbumPic modalVisible={picState} data={picDetails} handleVisible={handleVisible} />
      <Cropper
        // src={curUrl}
        ref={cropper}
        style={{height: 400, width: 100}}
        aspectRatio={1}
        guides={false}
        crop={_crop.bind(this)}
      />
    </Row>
  );
};

export default connect(({goods}) => ({
  goods
}))(AlbumUpload);
